<template>
  <div id="chat-box">
    <el-row class="chat-container">
      
      <el-col :span="24">
        <el-card shadow="never" class="chat-card">
          <el-timeline>
            <div class="avatar-bot" v-if="chatMessages.length == 0"">
                <i class="iconfont icon-bot"></i>
                <p class="avatar-text" style="font-size: 1.875rem;line-height: 2.25rem;font-family: Arial, sans-serif;color: #409eff;">嗨，我能帮你什么忙？</p>
            </div>
            
             <el-timeline-item
              v-for="(msg, index) in chatMessages"
              :key="index"
              :type="msg.role === 'user' ? '' : 'primary'"
              :timestamp="msg.formattedTimestamp"
            >
              <div class="message-container" :class="msg.role">
                <div class="avatar">
                  <svg v-if="msg.role === 'user'" class="user-avatar" viewBox="0 0 64 64">
                    <circle cx="32" cy="32" r="30" fill="#f0f9eb" />
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="32" fill="#409eff">U</text>
                  </svg>
                  <svg v-else class="bot-avatar" viewBox="0 0 64 64">
                    <circle cx="32" cy="32" r="30" fill="#eef1f6" />
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="32" fill="#409eff">B</text>
                  </svg>
                </div>
                <div class="message-content" v-html="msg.role === 'assistant' ? renderMarkdown(msg.content) : msg.content">
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item v-if="loading" type="primary">
              <div class="message-container assistant">
                <div class="avatar">
                  <svg class="bot-avatar" viewBox="0 0 64 64">
                    <circle cx="32" cy="32" r="30" fill="#eef1f6" />
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="32" fill="#409eff">B</text>
                  </svg>
                </div>
                <div class="message-content loading-content">
                  <el-spinner class="loading-spinner" type="ball-spin-clockwise" size="small"></el-spinner>
                </div>
              </div>
            </el-timeline-item>
            <el-timeline-item
              v-if="userInput"
              type="primary"
              :timestamp="currentInputTimestamp"
            >
              <div class="message-container user">
                <div class="avatar">
                  <svg class="user-avatar" viewBox="0 0 64 64">
                    <circle cx="32" cy="32" r="30" fill="#f0f9eb" />
                    <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="32" fill="#409eff">U</text>
                  </svg>
                </div>
                <div class="message-content user-message">
                  {{ userInput }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title="上传弹窗" :visible.sync="dialogFormVisible">
      <el-upload
      class="upload-pdf"
      drag
      action="http://127.0.0.1:30001/upload-pdf"
      multiple
      :limit="1"
      accept=".pdf"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传PDF文件，且不超过50MB。</div>
    </el-upload>
  </el-dialog>
    <el-row class="input-row" >
      <el-col :span="6" style="text-align: right; line-height: 62px;padding-right: 20px;"> 

      <el-button type="primary" round class="upload-button" @click="dialogFormVisible = true"">上传文件</el-button>
    </el-col>
    <el-col :span="18" style="text-align: left;">
        <el-input placeholder="请输入您的问题..."v-model="userInput" @keyup.enter.native="sendMessage" class="input-box">
            <el-select v-model="modelName" slot="prepend" placeholder="请选择" class="custom-model-select">
                <el-option label="清华智谱" value="zhipu"></el-option>
                <el-option label="阿里千问" value="qwen"></el-option>
                <el-option label="文档问答" value="ziwen"></el-option>
                <el-option label="测试助手" value="test"></el-option>
            </el-select>
            <el-button slot="append" class="input-button" icon="el-icon-top"  @click="sendMessage"></el-button>
      </el-input>
    </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios';
import marked from 'marked';

export default {
  data() {
    return {
      dialogFormVisible:false,
      modelName: 'test',
      userInput: '',
      chatMessages: [],
      currentInputTimestamp: '',
      loading: false, // 新增 loading 状态
    };
  },
  mounted() {
    console.log(this.chatMessages.length);
  },
  methods: {
    sendMessage() {
        if (this.userInput.trim() === '') {
            this.$message('请输入内容');
            return;
        }
      this.chatMessages.push({
        role: 'user',
        content: this.userInput,
        timestamp: new Date(),
        formattedTimestamp: this.formatDate(new Date()),
      });
      this.loading = true; // 发送消息后设置 loading 状态为 true
      if (this.modelName == 'ziwen') {
        axios.post('http://127.0.0.1:30001/query', { query: this.userInput })
        .then((response) => {
          console.log('Received answer:', response.data.answer);
          const answer = response.data.answer;
          this.chatMessages.push({
            role: 'assistant',
            content: answer,
            timestamp: new Date(),
            formattedTimestamp: this.formatDate(new Date()),
          });
          this.loading = false; // 接收到回复后设置 loading 状态为 false
        }).catch((error) => {
          console.error('Error:', error);
          this.chatMessages.push({
            role: 'system',
            content: '输入内容为空，请重新输入',
            timestamp: new Date(),
          });
          this.loading = false; // 发生错误时设置 loading 状态为 false
        });
      }
      else{
        axios
          .post('http://127.0.0.1:30001/ask', { content: this.userInput,modelName:this.modelName })
          .then((response) => {
            console.log('Received answer:', response.data.answer);
            const answer = response.data.answer;
            this.chatMessages.push({
              role: 'assistant',
              content: answer,
              timestamp: new Date(),
              formattedTimestamp: this.formatDate(new Date()),
            });
            this.loading = false; // 接收到回复后设置 loading 状态为 false
          })
          .catch((error) => {
            console.error('Error:', error);
            this.chatMessages.push({
              role: 'system',
              content: '输入内容为空，请重新输入',
              timestamp: new Date(),
            });
            this.loading = false; // 发生错误时设置 loading 状态为 false
          });
      }
      this.userInput = '';
    },
    formatDate(timestamp) {
      const formatter = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
      });
      return formatter.format(timestamp);
    },
    renderMarkdown(content) {
      return marked(content);
    }
  },
  watch: {
    userInput(newValue) {
      if (newValue) {
        this.currentInputTimestamp = this.formatDate(new Date());
      } else {
        this.currentInputTimestamp = '';
      }
    },
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.timeline {
  margin-bottom: 20px;
}

.message-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  margin-right: 10px;
}

.user .avatar {
  order: 2;
  margin-left: 10px;
  margin-right: 0;
}

.message-content {
  text-align: left;
  padding: 10px;
  border-radius: 5px;
  line-height: 1.5;
  max-width: 60%;
}

.loading-content {
  display: flex;
  align-items: center;
}

.loading-spinner {
  width: 24px;
  height: 24px;
}

.user {
  justify-content: flex-end;
}

.user .message-content {
  background-color: #f0f9eb;
  color: #33735f;
  text-align: right;
}

.assistant .message-content {
  background-color: #eef1f6;
  color:  #409eff;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}

.system .message-content {
  background-color: #f5f7fa;
  color: #909399;
}


.user-avatar,
.bot-avatar {
  width: 40px;
  height: 40px;
}

pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  white-space: pre-wrap; /* 允许代码换行 */
  word-wrap: break-word; /* 允许长单词换行 */
}

.input-box {
  width: 70%; /* 或者具体的像素宽度，比如 300px */
  height: auto; /* 保持高度自适应内容 */
  margin: 0 auto;
  border-radius: 10px; /* 根据需要调整圆角大小 */
  border: 1px solid transparent; /* 透明边框 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px; /* 内边距 */
  outline: none; /* 移除焦点时的轮廓线 */
  transition: border-color 0.3s, box-shadow 0.3s; /* 为过渡效果做准备 */
}

.input-box:hover {
  border-color: #409EFF; /* 鼠标悬停时边框变为蓝色 */
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2); /* 加强阴影效果 */
}

.input-row {
  margin-top: 20px;
}
.chat-card {
  /* 设置一个固定的最小高度，可以根据需要调整 */
  min-height: 800px;
  width: 80%;
  /* 当内容超出时显示滚动条 */
  overflow-y: auto;
  transform: translate(12%, 0%); 
  border-radius: 10px;
  border: 1px solid #ccc;
}

/* 可选：自定义滚动条样式，适用于Webkit内核浏览器 */
.chat-card::-webkit-scrollbar {
  width: 8px;
}

.chat-card::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

.chat-card::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
.custom-model-select{
    width: 120px;
}
.avatar-bot {
  position: absolute; /* 绝对定位 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); 
  height: 48px;
  line-height: 48px; /* 保证图标垂直居中 */
  text-align: center; /* 文本（图标）居中 */
}

.iconfont {
  font-size: 64px; 
  color: #409eff;
}
.upload-button { 
  padding: 12px 10px;
  right: 0px;
}

</style>
